<template>
	<view class="goods-manage">
		<gyd-navbar back-color="#fff" :title="title"></gyd-navbar>

		<u-form class="form" labelPosition="left" :model="formData" :rules="rules" :ref="formRef">
			<u-form-item class="form-item" label="商品名称" labelWidth="120" prop="name">
				<u-input v-model="formData.name" :maxlength="30" placeholder="请输入30字以内商品名称"></u-input>
			</u-form-item>

			<u-form-item class="form-item" label="商品品牌" labelWidth="120" prop="brand_id">
				<view class="value">
					<cus-selects :closeSelect.sync="false" :data="brandList" :value="formData.brand_id"
						placeholder="请输入关键字搜索" @change="changeBrand" :clearable="true" :filterable="true"
						:searchType='1'></cus-selects>
					<view class="tips">如未找到对应品牌请联系平台更新</view>
				</view>
			</u-form-item>

			<u-form-item class="form-item" label="商品分类" labelWidth="120" prop="category_id">
				<view class="value">
					<cus-selects :closeSelect.sync="false" :data="categoryList" :value="formData.category_id"
						placeholder="请输入关键字搜索" @change="changeCategory" :clearable="true" :filterable="true"
						:searchType='1'></cus-selects>
					<view class="tips" v-if="formData.category_id==12">请先创建关联水票的商品</view>
				</view>
			</u-form-item>

			<u-form-item class="form-item" label="可用水票商品" labelWidth="120" prop="goods_ids"
				v-if="formData.category_id==12">
				<zqs-select :multiple="true" :list="goodsList" :value="formData.goods_ids" label-key="label"
					value-key="value" placeholder=" 请选择可用水票商品" title="选择可用水票商品" clearable v-model="formData.goods_ids"
					@search="searchEvent" @change="selectChangeGoods"></zqs-select>
			</u-form-item>

			<u-form-item class="form-item" label="服务类型" labelWidth="120" prop="delivery_type">
				<uni-data-select v-model="formData.delivery_type" :localdata="deliveryTypeList"></uni-data-select>
			</u-form-item>

			<u-form-item class="form-item" label="单桶配送费" labelWidth="120" prop="delivery_price"
				v-if="formData.delivery_type == 1 || formData.delivery_type == 3">
				<view class="value">
					<u-input v-model="formData.delivery_price" placeholder="请输入"></u-input>
					<view class="tips">如果是一口价，配送费请设为0</view>
				</view>
			</u-form-item>

			<u-form-item class="form-item" label="单桶供给平台价" labelWidth="120" prop="cost_price">
				<u-input v-model="formData.cost_price" placeholder="请输入"></u-input>
			</u-form-item>

			<u-form-item class="form-item" label="单桶本地零售价" labelWidth="120" prop="sale_price">
				<u-input v-model="formData.sale_price" placeholder="请输入"></u-input>
			</u-form-item>

			<u-form-item class="form-item" label="库存" labelWidth="120" prop="stock">
				<view class="value">
					<u-input v-model="formData.stock" placeholder="请输入"></u-input>
					<view class="tips">如有其他平台一起售卖，库存建议不要修改</view>
				</view>
			</u-form-item>

			<u-form-item class="form-item" label="单位" labelWidth="120" prop="unit_id">
				<cus-selects :closeSelect.sync="false" :data="unitList" :value="formData.unit_id" placeholder="请输入关键字搜索"
					@change="changeUnit" :clearable="true" :filterable="true" :searchType='1'></cus-selects>
			</u-form-item>

			<u-form-item class="form-item" label="未开封有效期/月" labelWidth="120" prop="shelf_life_unopened">
				<u-input v-model="formData.shelf_life_unopened" placeholder="请输入"></u-input>
			</u-form-item>

			<u-form-item class="form-item" label="开封后建议使用/天" labelWidth="120" prop="shelf_life_opened">
				<u-input v-model="formData.shelf_life_opened" placeholder="请输入"></u-input>
			</u-form-item>

			<u-form-item class="form-item" label="送达时效/小时" labelWidth="120" prop="delivery_time"
				v-if="formData.delivery_type == 1 || formData.delivery_type == 3">
				<u-input v-model="formData.delivery_time" placeholder="请输入"></u-input>
			</u-form-item>

			<u-form-item class="form-item" label="发票服务" labelWidth="120" prop="invoice_type">
				<uni-data-select v-model="formData.invoice_type" :localdata="invoiceTypeList"></uni-data-select>
			</u-form-item>

			<u-form-item class="form-item" label="开票比例/%" labelWidth="120" prop="invoice_ratio"
				v-if="formData.invoice_type == 2">
				<u-input v-model="formData.invoice_ratio" placeholder="请输入"></u-input>
			</u-form-item>

			<u-form-item class="form-item" label="商品描述" labelWidth="120" prop="description">
				<u-textarea v-model="formData.description" placeholder="请输入"></u-textarea>
			</u-form-item>

			<u-form-item class="form-item" label="资质文件" labelWidth="120" prop="certs_ids">
				<view class="value" v-if="certList.length>0">
					<checkbox-group class="groupbox" @change="checkboxChange">
						<label class="item" v-for="(item,index) in certList" :key="index">
							<checkbox :value="item.id" :checked="item.checked" />{{item.name}}
						</label>
					</checkbox-group>
				</view>
				<view class="value" v-else>
					<button type="primary" size="mini" @click="uploadQualification">补充资质</button>
				</view>
			</u-form-item>

			<view class="upload">
				<view class="tips">封面图</view>
				<uni-file-picker v-model="imgList" return-type="array" file-mediatype="image" mode="grid"
					:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn :limit="1"
					@select="selectFile($event, 1)" @delete="removeOk($event, 1)">
					<view class="custom-upload" slot="addBtn">
						<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
					</view>
				</uni-file-picker>
			</view>
			<view class="upload">
				<view class="tips">产品详情图（最多5张）</view>

				<uni-file-picker v-model="imageLists" return-type="array" file-mediatype="image" mode="grid"
					:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn :limit="5"
					@select="selectFile($event, 2)" @delete="removeOk($event, 2)">
					<view class="custom-upload" slot="addBtn">
						<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
					</view>
				</uni-file-picker>
			</view>
		</u-form>

		<view class="footer">
			<view class="btn-group">
				<u-button class="btn" type="primary" size="large" block @click="submit()">保存</u-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';
	import cusSelects from '@/components/cus-selects-fan/cus-selects-fan.vue';

	const state = reactive({
		title: '水产品',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),
		goods_id: 0,
		flag: 'add',
		keyword: '',
		formData: {
			name: '',
			brand_id: 0,
			category_id: 0,
			delivery_price: '',
			cost_price: '',
			sale_price: '',
			delivery_type: '1',
			goods_ids: [],
			for_goods: '',
			stock: 999999,
			unit_id: '',
			shelf_life_unopened: 3,
			shelf_life_opened: 60,
			delivery_time: 1,
			invoice_type: '0',
			invoice_ratio: 3,
			description: '',
			certs_ids: [],
			for_certs: '',
			logo: '',
			images: '',
			shop_type: 2,
			store_id: 0,
			copy_id: 0,
		},
	});

	const rules = ref([]);
	const formRef = ref();
	const brandList = ref([]);
	const categoryList = ref([]);
	const goodsList = ref([]);
	const deliveryTypeList = ref([{
			text: '包含配送',
			value: '1'
		},
		{
			text: '不配送',
			value: '2'
		},
		{
			text: '配送+自提',
			value: '3'
		}
	]);
	const unitList = ref([]);
	const invoiceTypeList = ref([{
			text: '不提供发票',
			value: '0'
		},
		{
			text: '普票',
			value: '1'
		},
		{
			text: '专票',
			value: '2'
		}
	]);
	const certList = ref([]);
	const imgList = ref([]);
	const imageLists = ref([]);
	const extname = ref('jpg,jpeg,png,bmp,gif,tif,svg,webp');
	const imageStyles = ref({
		"width": '220rpx', // 边框宽度
		"height": '200rpx', // 边框高度
		"border": { // 如果为 Boolean 值，可以控制边框显示与否
			"color": "#909193", // 边框颜色
			"width": "1px", // 边框宽度
			"style": "solid", // 边框样式
		}
	});

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		let selStore = cache.get('selStore');
		if (selStore) {
			state.formData.store_id = selStore.id;
		}
		if (opt.hasOwnProperty('id')) {
			console.log('传递参数', opt.id);
			state.goods_id = opt.id;
		}
		if (opt.hasOwnProperty('flag')) {
			console.log('传递参数', opt.flag);
			state.flag = opt.flag;
		}
		initData();
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	})

	onReachBottom(() => {
		console.log('触底加载更多');
	})

	function initData() {
		getBrandList();
		getCategoryList();
		getGoodsList();
		getUnitList();
		getCertList();
		setTimeout(() => {
			getDetail();
		}, 1000);
	}

	function getBrandList() {
		request.get('merchant.product/getBrandList', {
			shop_type: state.formData.shop_type
		}).then(res => {
			console.log('品牌', res);
			let data = res.data;
			data.forEach((item, index) => {
				brandList.value.push({
					text: item.name,
					label: item.name,
					value: item.id + ''
				});
			})
		})
	}

	function getCategoryList() {
		request.get('merchant.product/getCategoryList', {
			shop_type: state.formData.shop_type
		}).then(res => {
			console.log('分类', res);
			let data = res.data;
			data.forEach((item, index) => {
				categoryList.value.push({
					text: item.name,
					label: item.name,
					value: item.id + ''
				});
			})
		})
	}

	function getGoodsList() {
		request.get('merchant.product/goodsList', {
			keyword: state.keyword,
			store_id: state.formData.store_id,
			shop_type: state.formData.shop_type,
			typeInfo: 1,
			limit: 50
		}).then(res => {
			console.log('商品列表', res);
			res.data.data.forEach(item => {
				goodsList.value.push({
					text: item.name,
					label: item.name,
					value: item.id + ''
				})
			})
		})
	}

	function getUnitList() {
		request.get('merchant.product/getUnitList', {}).then(res => {
			console.log('单位', res);
			let data = res.data;
			data.forEach((item, index) => {
				unitList.value.push({
					text: item.name,
					label: item.name,
					value: item.id + ''
				});
			})
		})
	}

	function getCertList() {
		request.get('store.credential/list', {
			store_id: state.formData.store_id
		}).then(res => {
			console.log('资质', res);
			certList.value = res.data.data;
			certList.value.forEach(item => {
				item.id = item.id + '';
			})
		})
	}

	function getDetail() {
		if (!state.goods_id) {
			return
		}
		uni.showLoading({
			title: '加载中'
		});
		request.get('goods/detail', {
			goods_id: state.goods_id
		}).then(res => {
			console.log('详情', res);
			uni.hideLoading();
			if (res.code == 1) {
				state.formData = res.data;
				state.formData.brand_id = res.data.brand_id + '';
				state.formData.category_id = res.data.category_id + '';
				state.formData.unit_id = res.data.unit_id + '';
				state.formData.delivery_type = res.data.delivery_type + '';
				state.formData.invoice_type = res.data.invoice_type + '';
				imgList.value = [{
					name: res.data.logo,
					extname: 'png',
					url: util.requestUrl() + res.data.logo,
				}];
				let pro_img_list = res.data.imagesList;
				pro_img_list.forEach(item => {
					imageLists.value.push({
						name: item,
						extname: 'png',
						url: util.requestUrl() + item,
					})
				});
				console.log('详情图', imageLists.value);
				certList.value.forEach((cert, x) => {
					res.data.certs_ids.forEach((item, y) => {
						if (cert.id == item) {
							cert.checked = true;
						}
					})
				});
				console.log('资质', certList.value);

				// 复制商品，需要把商品ID移除
				if (state.flag == 'copy') {
					state.formData.copy_id = state.formData.id;
					state.formData.id = 0;
				}
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none',
					mask: true
				})
			}
		})
	}

	function changeBrand(e) {
		console.log('选择产品品牌', e);
		state.formData.brand_id = e;
	}

	function changeCategory(e) {
		console.log('选择产品分类', e);
		state.formData.category_id = e;
	}

	function changeUnit(e) {
		console.log('选择产品单位', e);
		state.formData.unit_id = e;
	}

	function checkboxChange(e) {
		console.log('选择资质文件', e);
		let array = e.detail.value;
		state.formData.certs_ids = array;
		state.formData.for_certs = ',' + array.join(',') + ',';
	}

	function uploadQualification() {
		// 保存到缓存
		savaHitory();

		// 跳转资质上传页面
		pageRoute(`/merchantPages/store-manage/certif-form`);
	}

	// 保存历史
	function savaHitory() {
		cache.set('waterGoods', state.formData);
	}

	// 获取历史
	function getHitory() {
		state.formData = cache.get('waterGoods');
	}

	function submit() {
		let check = checkData();
		console.log('验证表单', check);
		if (!check) {
			return;
		}
		//处理商品
		/* state.formData.goods_ids.forEach((item, index) => {
			if (index == 0) {
				state.formData.for_goods = ',' + item + ',';
			} else {
				state.formData.for_goods += item + ',';
			}
		}) */
		if (state.formData.goods_ids.length > 0) {
			state.formData.for_goods = ',' + state.formData.goods_ids.join(',') + ',';
		}
		//处理图片
		if (imgList.value.length > 0) {
			state.formData.logo = imgList.value[0].name;
		}
		imageLists.value.forEach((item, index) => {
			if (index == 0) {
				state.formData.images = item.name;
			} else {
				state.formData.images += "," + item.name;
			}
		})
		console.log('提交表单数据', state.formData);

		request.post('merchant.product/save', state.formData).then(res => {
			console.log('创建商品', res);
			util.showTip(res.msg);
			if (res.code == 1) {
				setTimeout(() => {
					pageRoute('/merchantPages/goods-manage/goods-manage');
				}, 1000);
			}
		})
	}

	function checkData() {
		if (!state.formData.name) {
			util.showTip('请输入30字以内商品名称');
			return false;
		}
		if (!state.formData.brand_id) {
			util.showTip('请选择商品品牌');
			return false;
		}
		if (!state.formData.category_id) {
			util.showTip('请选择商品分类');
			return false;
		}
		if (state.formData.category_id == 12) {
			if (state.formData.goods_ids.length <= 0) {
				util.showTip('请选择可用水票商品');
				return false;
			}
		}
		if (!state.formData.delivery_type) {
			util.showTip('请选择服务类型');
			return false;
		}
		if (state.formData.delivery_type == 1 || state.formData.delivery_type == 3) {
			if (!state.formData.delivery_price) {
				util.showTip('请输入单桶配送费');
				return false;
			}
		}
		if (!state.formData.cost_price) {
			util.showTip('请输入成本价');
			return false;
		}
		if (!state.formData.sale_price) {
			util.showTip('请输入销售价');
			return false;
		}
		if (!state.formData.stock) {
			util.showTip('请输入库存');
			return false;
		}
		if (!state.formData.unit_id) {
			util.showTip('请选择单位');
			return false;
		}
		if (!state.formData.shelf_life_unopened) {
			util.showTip('请输入未开封有效期/月');
			return false;
		}
		if (!state.formData.shelf_life_opened) {
			util.showTip('请输入开封后建议使用/天');
			return false;
		}
		if (!state.formData.delivery_time) {
			util.showTip('请输入送达时效/小时');
			return false;
		}
		if (state.formData.invoice_type == 2) {
			if (!state.formData.invoice_ratio) {
				util.showTip('请输入开票比例/%');
				return false;
			}
		}
		if (state.formData.certs_ids.length <= 0) {
			util.showTip('请选择资质文件');
			return false;
		}
		if (imgList.value.length <= 0) {
			util.showTip('请上传封面图');
			return false;
		}
		if (imageLists.value.length <= 0) {
			util.showTip('请上传产品详情图');
			return false;
		}
		return true;
	}

	// 选择图片
	function selectFile(res, flag) {
		console.log('selectFile', res, flag);

		// 上传
		for (let i = 0; i < res.tempFilePaths.length; i++) {
			upload(res.tempFilePaths[i], flag);
		}
	}

	// 删除照片
	function removeOk(res, flag) {
		console.log('removeOk', res, flag);
		if (flag == 1) {
			state.formData.logo = "";
			imgList.value = [];
		}
		if (flag == 2) {
			imageLists.value.splice(res.index, 1);
		}
	}

	// 图片上传
	function upload(file, flag) {
		let type = "waterGoods";
		uni.uploadFile({
			url: util.requestUrl() + '/api/upload/uploadfile', // 开发者服务器接口地址
			filePath: file, // 要上传文件资源的路径
			name: 'file', // 文件对应的 key
			formData: {
				'type': type,
				'token': cache.get('M_LOGIN_TOKEN', false) || '',
				'role': cache.get('role', false) || 0,
			}, // 请求的 form data
			success: (res) => {
				const json = JSON.parse(res.data);
				if (json.code == 1) {
					const data = json.data;
					console.log('上传成功', data);
					util.showTip(data.originalName + '上传成功');
					// 处理上传成功的结果
					if (flag == 1) {
						state.formData.logo = data.url;
						imgList.value = [{
							name: data.url,
							extname: data.fileType, // 文件类型，image/video/file
							url: data.url2,
						}];
					}

					if (flag == 2) {
						imageLists.value.push({
							name: data.url,
							extname: data.fileType,
							url: data.url2,
						});
					}
				}
			},
			fail: (error) => {
				console.error('上传失败', error);
				// 处理上传失败的错误
				uni.showToast({
					title: '网络错误，请稍后再试！',
					icon: fail,
					duration: 2000
				})
			}
		});
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		goods_id,
		flag,
		keyword,
		formData,
	} = toRefs(state);
</script>

<style lang="scss">
	.goods-manage {
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));

		.form {
			padding: $m24;

			.form-item {
				background: #fff;
				margin-bottom: $m16;
				padding: 0 $m24;
				border-radius: 10rpx;

				.value {
					.tips {
						padding: 12rpx 0;
						font-size: 20rpx;
						color: $tips-color;
					}
				}
			}
		}

		.footer {
			position: fixed;
			/* 固定在底部 */
			bottom: 0;
			width: 100%;

			.btn-group {
				.btn {}
			}
		}
	}
</style>